package NIO.blocking;
/*
 * @Author  Wrial
 * @Date Created in 13:04 2020/4/11
 * @Description 本质还是Stream
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SocketChannel;

public class ChannelClient {
    public static void main(String[] args) throws IOException {

        new ChannelClient(8090).sendMsg();
    }

    private SocketChannel socketChannel;

    public ChannelClient(int port) throws IOException {
        init(port);
    }

    private void init(int port) throws IOException {
        socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8090));
        System.out.println("client init ");

    }

    private PrintWriter getWriter(Socket socket) throws IOException {
        // true是自动刷新
        return new PrintWriter(socket.getOutputStream(), true);
    }

    private BufferedReader getReader(Socket socket) throws IOException {
        return new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    private void sendMsg() throws IOException {
        BufferedReader bufferedReader = getReader(socketChannel.socket());
        PrintWriter printWriter = getWriter(socketChannel.socket());

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String sendMsg;
        while ((sendMsg = reader.readLine()) != null) {
            printWriter.println(sendMsg);
            System.out.println(bufferedReader.readLine());
            if (sendMsg.equals("end")) {
                System.out.println("end");
                break;
            }
        }
        if (socketChannel != null) socketChannel.close();
    }


}
